import os
import json

"""本文件放弃思考，纯人工添加判断"""

DATA_DIR = "oldData"

pool_info = json.load(open("resource/pool_info.json", "r", encoding="utf-8"))
char_info = json.load(open("resource/char_info.json", "r", encoding="utf-8"))

spring_fest = [
    "炽吾生平",
    "千秋一粟",
    "万象伶仃",
    "浊酒澄心",
    "月隐晦明",
    "地生五金 复刻",
    "地生五金"
]
anniver_fest = [
    "布道自由",
    "恶人寥寥",
    "何以为我",
    "宿愿",
    "真理孑然",
    "斩荆辟路",
    "海蚀",
    "循光道途",
    "深悼",
    "勿忘我",
    "遗愿焰火",
]
summer_fest = [
    "在流沙上刻印",
    "云间清醒梦",
    "巨斧与笔尖",
    "盛夏新星"
]
# 读取旧版本数据
# 扫描目录下的所有
for file_name in os.listdir(DATA_DIR):
    # 读取
    old_data = json.load(open(os.path.join(DATA_DIR, file_name), "r", encoding="utf-8"))

    # 新数据
    new_data_list = []
    last_ts = 0
    last_pos = 0
    # 旧数据中的每抽遍历
    for key in reversed(list(old_data.keys())):

        if key in ["uid", "nickName"]:
            continue
        value = old_data[key]
        new_gachaTs = value["time"]
        new_charName = value["name"]
        new_rarity = value["rarity"]
        if value["pool"] == "常驻标准寻访":
            new_poolName = "标准寻访"
        else:
            new_poolName = value["pool"]
        new_isNew = value["isNew"]

        for pool in pool_info.values():
            # print(json.dumps(pool))
            if new_poolName in pool["name"] and pool["openTs"] < new_gachaTs < pool["endTs"]:
                new_poolId = pool["id"]
                # print(f"池子是{new_poolId}")
                break
        if "new_poolId" not in locals():

            list_s = []
            for pool in pool_info.values():
                if pool["openTs"] < new_gachaTs < pool["endTs"]:
                    list_s.append(pool["id"])

            for list_item in list_s:
                if "专属推荐干员寻访" in value["pool"]:
                    input_select = "BOOT_0_1_1"
                if "联合" in value["pool"] and "联合" in pool_info[list_item]["picName"]:
                    input_select = list_item
                if "中坚" in value["pool"] and "中坚" in pool_info[list_item]["picName"] and "CLASSIC" in list_item:
                    input_select = list_item
                if "前路回响" in value["pool"] and "前路回响" in pool_info[list_item]["picName"]:
                    input_select = list_item
                if "进攻-防守-战术交汇" in value["pool"] and "战术交汇" in pool_info[list_item]["picName"] and "LINKAGE" in list_item:
                    input_select = list_item
            if "input_select" not in locals():
                print(f"未找到对应池子，卡池名：{new_poolName}，卡池时间：{new_gachaTs}，数据：{value}")
                print(f"可能对应的池子有：{json.dumps(list_s, ensure_ascii=False)}")
                input_select = list_s[int(input("请输入（从0开始）："))]
                if input_select == "":
                    print("输入为空，结束脚本")
                    break
            # print(f"卡池  {value} 可能为 {list_s}   修正为  {input_select}")
            new_poolId = input_select
            del input_select

        if last_ts == new_gachaTs:
            # 如果是十连中的第2-10抽
            last_pos = last_pos + 1
        else:
            # 如果遇到新的十连或者单抽
            last_pos = 0
        new_pos = last_pos

        if "麒麟X夜刀" in new_charName:
            new_charId = "char_1029_yato2"
        for char in char_info.values():
            if new_charName == char["name"]:
                new_charId = char["id"]
                break
        if "new_charId" not in locals():
            print("未找到对应角色")
            print(f"角色名：{new_charName}，数据：{value}")
            break

        # 将新数据写入
        new_data = {
            "poolId": new_poolId,
            "poolName": new_poolName,
            "charId": new_charId,
            "charName": new_charName,
            "rarity": new_rarity - 1,
            "isNew": new_isNew,
            "gachaTs": str(new_gachaTs * 1000),
            "pos": new_pos
        }
        del new_poolId, new_charId
        new_data_list.insert(0, new_data)
        # 最后将本抽的时间保存，用于判断下一抽是否为同一个十连
        last_ts = new_gachaTs

    new_data_list_has_cate = {}
    for new_gacha_data in new_data_list:
        if new_gacha_data["poolId"].split("_")[0] in ["NORM", "SINGLE", "DOUBLE", "SPECIAL"]:
            gacha_cate = "normal"
        elif new_gacha_data["poolName"] in spring_fest:
            gacha_cate = "spring_fest"
        elif new_gacha_data["poolName"] in anniver_fest:
            gacha_cate = "anniver_fest"
        elif new_gacha_data["poolName"] in summer_fest:
            gacha_cate = "summer_fest"
        elif "CLASSIC" in new_gacha_data["poolId"]:
            gacha_cate = "classic"
        elif "ATTAIN" in new_gacha_data["poolId"]:
            gacha_cate = "attain"
        elif "LINKAGE" in new_gacha_data["poolId"]:
            gacha_cate = "linkage"
        elif "BOOT" in new_gacha_data["poolId"]:
            gacha_cate = "newbee"
        else:
            print("未找到对应卡池类型")
            print(json.dumps(new_gacha_data, ensure_ascii=False))
            break
        if gacha_cate not in new_data_list_has_cate:
            new_data_list_has_cate[gacha_cate] = []
        new_data_list_has_cate[gacha_cate].insert(0, new_gacha_data)
    new_data_list_has_cate["uid"] = old_data["uid"]
    new_data_list_has_cate["nickName"] = old_data["nickName"]

    # 旧数据格式化，开始与新数据合并
    new_datav3_path = os.path.join("data", f"test{file_name}")

    if os.path.exists(new_datav3_path):
        print(f"{new_datav3_path} 存在，开始合并")
        # 存在新数据就开始合并
        datav3 = json.loads(open(new_datav3_path, "r", encoding="utf-8").read())
        for __key, __gacha_cate in datav3.items():
            if __key in new_data_list_has_cate:
                print(f"合并 {__key} 数据")
                cate_last_ts = __gacha_cate[0]["gachaTs"]
                __index = 0
                for new_gachav2_data_with_cate in new_data_list_has_cate[__key]:
                    if int(new_gachav2_data_with_cate["gachaTs"][:-3]) >= int(cate_last_ts[:-3])\
                            and __gacha_cate[0]["charName"] == new_gachav2_data_with_cate["charName"]\
                            and __gacha_cate[0]["pos"] == new_gachav2_data_with_cate["pos"]:
                        # print(f"{int(new_gachav2_data_with_cate["gachaTs"][:-3])} >= {int(cate_last_ts[:-3])}")
                        print(f"检测到截取的下标 {str(__index)} 数组为 {new_data_list_has_cate[__key][__index]}")
                        splice_list = new_data_list_has_cate[__key][:__index]
                        splice_list.extend(__gacha_cate)
                        new_data_list_has_cate[__key] = splice_list
                        break
                    elif len(new_data_list_has_cate[__key]) <= __index + 1:
                        new_data_list_has_cate[__key].extend(__gacha_cate)
                    __index = __index + 1

    with open(f"oldData/new_{old_data["uid"]}.json", "w", encoding="utf-8") as f:
        f.write(json.dumps(new_data_list_has_cate, indent=4, ensure_ascii=False))
    # print(json.dumps(new_data_list_has_cate, ensure_ascii=False))
